package com.zhong.thesimpleconnection.util;

import android.util.Log;

/**
 * Created by 俊峰 on 2017/5/17.
 */

public class getToBytes {

    /**
     * 将字符串变换为二进制表现
     * @param data 原始数据
     * @return 返回其二进制表现
     */
    public static byte[] getByte(String data){
        int length = data.length();
        byte[] allByte = new byte[length * 8];
        byte[] bytes = data.getBytes();
        for (int i = 1; i <= length; i++) {
            toBinary(bytes[i - 1], allByte, i);
        }
        for (byte b : allByte) {
            Log.d("Hello", "getByte: " + b);
        }
        return allByte;
    }

    private static void toBinary(byte number, byte[] allByte, int index){
        index = index * 8 - 1;
        for (int i = 0; i < 8; i++) {
            byte result = (byte) (number % 2);
            number = (byte) (number / 2);
            allByte[index - i] = result;
        }
    }

    /**
     * 将二进制表现转换为byte数据
     * @param binary 二进制表现
     * @return 返回其byte数据
     */
    public static byte[] backFromBinary(byte[] binary){
        int i = binary.length / 8;
        byte[] ret = new byte[i];
        for (int j = 0; j < i; j++) {
            for (int k = 0; k < 8; k++) {
                ret[j] = (byte) (ret[j] + binary[j * 8 + k] * Math.pow(2, (7 - k)));
            }
        }
        return ret;
    }

}
